package agentV1

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"
	"github.com/spf13/cast"
	"hc_server/pkg/app"
	pkgFile "hc_server/pkg/file"
	"hc_server/pkg/util"
	"hc_server/routers/api"
	"hc_server/routers/service/user"
	"hc_server/runtime/e"
)

type UserLoginForm struct {
	Password string `form:"password" valid:"Required;MaxSize(100)"`
	Mobile   string `form:"mobile" valid:"Required;MaxSize(11)"`
	Ip       string `form:"ip"`
}

// UserLogin godoc
// @Summary 用户登录
// @Description 用户登录
// @Tags 用户
// @Accept  json
// @Produce  json
// @Param   password query  string  false "密码 default" Enums(123123, 456456, 789789)
// @Param   mobile query  string  false "手机号 valid" minlength(5)  maxlength(10)
// @Param   ip query  string  false "ip地址 enums" default(127.0.0.1)
// @Param   collection  query     []string   false  "string collection"  collectionFormat(multi)
// @Param   extensions  query     []string   false  "string collection"  extensions(x-example=test,x-nullable)
// @Success 200 {object} app.Response
// @Failure 500 {object} app.Response
// @Router /api/v1/user/login [post]
func UserLogin(c *gin.Context) {
	appG := app.Gin{C: c}
	var (
		form    UserLoginForm
		errCode int
	)

	_, errCode = app.BindAndValid(c, &form)
	if errCode != e.SUCCESS {
		appG.ResponseError(e.CodeMap[errCode], nil)
		return
	}

	userService := user.User{
		Password: form.Password,
		Mobile:   form.Mobile,
	}

	result, err := userService.UserLogin()
	if err != nil {
		appG.ResponseError(err.Error(), nil)
		return
	}

	avatar := result["avatar"]
	if len(avatar) > 0 {
		avatar = pkgFile.GetImageFullUrl(avatar, result["id"])
		result["avatar"] = avatar
	}

	userService.ID = cast.ToInt(result["id"])
	err = userService.UserEdit(map[string]interface{}{"ip": c.ClientIP()})
	if err != nil {
		logrus.Error(fmt.Sprintf("/api/v1/user/login ip地址保存失败 %v err:%v", userService, err.Error()))
	}

	token, err := util.GenerateToken(userService.Mobile, userService.Password, "1")
	if err != nil {
		logrus.Error(fmt.Sprintf("/api/v1/user/login 获取token %v err:%v", userService, err.Error()))
		appG.ResponseError("token获取失败", nil)
		return
	}

	appG.ResponseLoginSuccess("登录成功", result, token)
}

type UserAddForm struct {
	Password string `form:"password" valid:"Required;MaxSize(100)"`
	Mobile   string `form:"mobile" valid:"Required;MaxSize(11)"`
	NickName string `form:"nickName"`
	RealName string `form:"realName"`
	Sex      string `form:"sex" valid:"Required;MaxSize(1)"`
	Remark   string `form:"remark"`
}

// @Summary 注册
// @Produce  json
// @Param password query string false "密码"
// @Param nick_name query string false "昵称"
// @Param mobile query string false "手机号码"
// @Param real_name query string false "真实姓名"
// @Param sex query int false "性别: 1=男 2=女"
// @Param avatar query string false "头像"
// @Param remark query string false "备注"
// @Success 200 {object} app.Response
// @Failure 500 {object} app.Response
// @Router /api/v1/user/add [post]

func UserAdd(c *gin.Context) {
	appG := app.Gin{C: c}
	var (
		form    UserAddForm
		errCode int
	)

	_, errCode = app.BindAndValid(c, &form)
	if errCode != e.SUCCESS {
		appG.ResponseError(e.CodeMap[errCode], nil)
		return
	}

	file, image, avatarErr := c.Request.FormFile("avatar")
	if avatarErr != nil {
		logrus.Error(fmt.Sprintf("/api/v1/user/add 图片解析失败 err:%s", avatarErr.Error()))
		appG.ResponseError("图片解析失败", nil)
		return
	}

	fileName, _, err := api.VerifyFile(file, image, c, "", "")
	if err != nil {
		logrus.Error(fmt.Sprintf("/api/v1/user/add 图片保存失败 err:%s", err.Error()))
		appG.ResponseError("图片保存失败", nil)
		return
	}

	_, errCode = app.BindAndValid(c, &form)
	if errCode != e.SUCCESS {
		appG.ResponseError(e.CodeMap[errCode], nil)
		return
	}

	userService := user.User{
		Password: form.Password,
		Mobile:   form.Mobile,
		NickName: form.NickName,
		RealName: form.RealName,
		Sex:      cast.ToInt(form.Sex),
		Remark:   form.Remark,
		Avatar:   fileName,
	}

	//添加用户前判断数据完整
	exists, err := userService.UserAddVerify()
	if !exists {
		logrus.Error(fmt.Sprintf("/api/v1/user/add 添加用户前判断数据完整 err:%s", err.Error()))
		appG.ResponseError(err.Error(), nil)
		return
	}

	//通过手机号码查询
	exists, err = userService.ExistByMobile()
	if err != nil {
		logrus.Error(fmt.Sprintf("/api/v1/user/add 通过手机号码查询 err:%s", err.Error()))
		appG.ResponseError(err.Error(), nil)
		return
	}
	if exists {
		logrus.Error("/api/v1/user/add 此手机号码已存在")
		appG.ResponseError("此手机号码已存在", nil)
		return
	}

	//添加用户
	userId, err := userService.UserAdd()
	if err != nil {
		logrus.Error(fmt.Sprintf("/api/v1/user/add 添加用户 err:%s", err.Error()))
		appG.ResponseError("注册失败", nil)
		return
	}

	//头像从临时空间移动到用户的文件夹
	err = pkgFile.MoveFileTempToUser(userId, fileName)
	if err != nil {
		logrus.Error(fmt.Sprintf("/api/v1/user/add err:%s", err.Error()))
		appG.ResponseError("保存图片失败", nil)
		return
	}

	if err != nil {
		logrus.Error(fmt.Sprintf("/api/v1/user/add 头像上传失败 err:%s", err.Error()))
		appG.ResponseError("头像上传失败", nil)
		return
	}

	appG.ResponseSuccess("注册成功", map[string]interface{}{})
}

type UserEditForm struct {
	Id       string `form:"id"`
	Password string `form:"password"`
	Mobile   string `form:"mobile"`
	NickName string `form:"nickName"`
	RealName string `form:"realName"`
	Sex      string `form:"sex"`
	Avatar   string `form:"avatar"`
	Remark   string `form:"remark"`
}

// @Summary 编辑 昵称、真实姓名、手机号码、性别
// @Produce  json
// @Param id query string false "用户id"
// @Param nick_name query string false "昵称"
// @Param mobile query string false "手机号码"
// @Param real_name query string false "真实姓名"
// @Param sex query int false "性别: 1=男 2=女"
// @Param remark query string false "备注"
// @Success 200 {object} app.Response
// @Failure 500 {object} app.Response
// @Router /api/v1/user/edit [post]

func UserEdit(c *gin.Context) {
	appG := app.Gin{C: c}
	var (
		form    UserEditForm
		errCode int
	)

	_, errCode = app.BindAndValid(c, &form)
	if errCode != e.SUCCESS {
		appG.ResponseError(e.CodeMap[errCode], nil)
		return
	}

	userService := user.User{
		ID:       cast.ToInt(form.Id),
		NickName: form.NickName,
		RealName: form.RealName,
		Sex:      cast.ToInt(form.Sex),
		Remark:   form.Remark,
	}

	mapd := userService.GetUserEditMap()
	if len(mapd) == 0 {
		logrus.Error(fmt.Sprintf("/api/v1/user/edit 缺少必要参数 userService:%v", userService))
		appG.ResponseError("缺少必要参数", nil)
		return
	}

	exist, err := userService.ExistByID()
	if err != nil {
		logrus.Error(fmt.Sprintf("/api/v1/user/edit 此用户不存在 userService:%v err:%s", userService, err.Error()))
		appG.ResponseError("此用户不存在", nil)
		return
	}

	if !exist {
		logrus.Error(fmt.Sprintf("/api/v1/user/edit 此用户不存在 userService:%v", userService))
		appG.ResponseError("此用户不存在", nil)
		return
	}

	err = userService.UserEdit(mapd)
	if err != nil {
		logrus.Error(fmt.Sprintf("/api/v1/user/edit 修改失败 userService:%v err:%s", userService, err.Error()))
		appG.ResponseError("修改失败", nil)
		return
	}

	appG.ResponseSuccess("修改成功", nil)
}

// @Summary 编辑头像
// @Produce  json
// @Param id query string false "用户id"
// @Param avatar query string false "头像"
// @Success 200 {object} app.Response
// @Failure 500 {object} app.Response
// @Router /api/v1/user/edit/avatar [post]

func UserEditAvatar(c *gin.Context) {

}

type UserEditPasswordForm struct {
	Id   string `form:"id" valid:"Required;MaxSize(10)"`
	Opwd string `form:"oPwd" valid:"Required;MaxSize(100)"`
	Npwd string `form:"nPwd" valid:"Required;MaxSize(100)"`
}

// @Summary 编辑密码
// @Produce  json
// @Param id query string false "用户id"
// @Param password query string false "密码"
// @Success 200 {object} app.Response
// @Failure 500 {object} app.Response
// @Router /api/v1/user/edit/password [post]

func UserEditPassword(c *gin.Context) {
	appG := app.Gin{C: c}
	var (
		form    UserEditPasswordForm
		errCode int
	)

	_, errCode = app.BindAndValid(c, &form)
	if errCode != e.SUCCESS {
		appG.ResponseError(e.CodeMap[errCode], nil)
		return
	}

	userService := user.User{ID: cast.ToInt(form.Id), Password: form.Opwd}

	exist, err := userService.ExistByID()
	if err != nil {
		logrus.Error(fmt.Sprintf("/api/v1/user/edit 此用户不存在 userService:%v err:%s", userService, err.Error()))
		appG.ResponseError("此用户不存在", nil)
		return
	}

	if !exist {
		logrus.Error(fmt.Sprintf("/api/v1/user/edit 此用户不存在 userService:%v", userService))
		appG.ResponseError("此用户不存在", nil)
		return
	}

	err = userService.EditUserPassword(form.Npwd)
	if err != nil {
		appG.ResponseError(err.Error(), nil)
	}

	appG.ResponseSuccess("修改成功", nil)
}
